package com.atguigu.srb.core.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.atguigu.srb.core.mapper.DictMapper;
import com.atguigu.srb.core.pojo.entity.dto.ExcelDictDTO;
import com.google.errorprone.annotations.Var;
import com.sun.org.apache.bcel.internal.generic.NEW;
import lombok.NoArgsConstructor;

import java.util.ArrayList;
import java.util.List;

@NoArgsConstructor
public class ExcelDictDTOListener  extends AnalysisEventListener<ExcelDictDTO> {

     DictMapper  dictMapper;
    //批量插入数据 首先要建一个数组
   List<ExcelDictDTO>  list=  new ArrayList<>();
   //每隔五条数据插入数据库一次
    static  final  int BATCH_COUNT=5;

    public ExcelDictDTOListener(DictMapper dictMapper) {
        this.dictMapper = dictMapper;
    }

    @Override
    public void invoke(ExcelDictDTO excelDictDTO, AnalysisContext analysisContext) {
          //批量插入数据
        list.add(excelDictDTO);
        if (list.size() >= BATCH_COUNT){
            //执行mapper 操作
            saveData();
            list.clear();
        }

    }

    private void saveData() {
      dictMapper.insertBatch(list);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
           //不满足五条数据 再调用一下 将所有数据插入
        saveData();
    }
}
